package com.jilefojing.session.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.enums.PlatformEnum;
import com.jilefojing.beans.enums.ThirdPartyTypeEnum;
import com.jilefojing.beans.enums.forusersession.TypeEnumForUserSession;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.UserSession;
import com.jilefojing.beans.pojos.enhanced.EnhancedUser;
import com.jilefojing.beans.pojos.enhanced.EnhancedUserSession;
import com.jilefojing.context.beans.vo.RememberMe;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.service.IUserService;
import com.jilefojing.session.service.ILoginService;
import com.jilefojing.session.service.IUserSessionService;
import com.jilefojing.util.Detect;
import com.jilefojing.util.MD5Util;

/**
 * @author jgshun
 * @date 2016-4-14 上午9:58:30
 * @version 1.0
 */
@Service
public class LoginService implements ILoginService {
	@Autowired
	private IUserSessionService userSessionService;
	@Autowired
	private IUserService userService;

	private final static Logger _LOGGER = LoggerFactory.getLogger(LoginService.class);

	@Override
	public EnhancedUserSession loginByRemeberMe(RememberMe rememberMe, UserContext userContext) throws UserContextException {
		EnhancedUser enhancedUserInfo = userService.getEnhancedUser(rememberMe.getSer().getEnhancedUser().getId());
		String account = null;
		ThirdPartyTypeEnum thirdPartyType = null;
		// if (!Detect.notEmpty(enhancedUserInfo.getPassword())) {
		// account = enhancedUserInfo.getThirdpartyid();
		// thirdPartyType = enhancedUserInfo.getThirdpartytype();
		// } else {
		account = Detect.notEmpty(enhancedUserInfo.getTelphone()) ? enhancedUserInfo.getTelphone() : Detect.notEmpty(enhancedUserInfo.getEmail()) ? enhancedUserInfo.getEmail() : Detect
				.notEmpty(enhancedUserInfo.getName()) ? enhancedUserInfo.getName() : "***********************";
		// }
		return this.loginWithNoPassword(account, thirdPartyType, PlatformEnum.getPlatformEnumByValue(rememberMe.getSer().getPlatform().getValue()), rememberMe.getSer().getDeviceId(), true,
				userContext);
	}

	private EnhancedUserSession login(String account, String password, boolean isUsePassword, boolean isEncoded, ThirdPartyTypeEnum thirdPartyType, PlatformEnum platform, String deviceId,
			boolean isRM, UserContext userContext) throws UserContextException {

		EnhancedUser enhancedUserInfo = null;
		if (thirdPartyType == null || thirdPartyType == ThirdPartyTypeEnum.UNKNOWN) {
			enhancedUserInfo = userService.getEnhancedUserByAccount(account);
		} else {
			enhancedUserInfo = userService.getEnhancedUserByThirdParty(account, thirdPartyType, userContext);
			isUsePassword = false;
		}
		if (isUsePassword) {
			if (!Detect.notEmpty(password)) {
				throw new UserContextException("密码不能为空");
			}
			if (!isEncoded) {
				password = MD5Util.getMD5Str(password);
			}
			if (!password.equals(enhancedUserInfo.getPassword())) {
				throw new UserContextException(ResponseEnum.PASSWORD_ERROR);
			}
		}

		TypeEnumForUserSession type = thirdPartyType == null ? TypeEnumForUserSession.jilefojing : TypeEnumForUserSession.getByValue(thirdPartyType.getValue());
		PlatformEnum platformEnumForUserSession = PlatformEnum.getPlatformEnumByValue(platform.getValue());
		UserSession userSession = userSessionService.convetnEnhancedUserSessionToUserSession(userSessionService.generateEnhancedUserSession(enhancedUserInfo.getId(), type, deviceId,
				platformEnumForUserSession, isRM, null));

		EnhancedUserSession enhancedUserSession = userSessionService.save(userSession);

		// 不仅手机端要验证 放在这个方法里updateUserSessionStatusForOnlyOneOnline
		// if (platform == PlatformEnum.ANDROID || platform ==
		// PlatformEnum.IPHONE) {
		// if (Detect.notEmpty(deviceId)
		// && !deviceId.equals(enhancedUserInfo.getDeviceid())) {
		// com.gk.beans.entity.UserInfo _userInfo = new
		// com.gk.beans.entity.UserInfo();
		// _userInfo.setUserId(enhancedUserInfo.getId());
		// _userInfo.setDeviceId(enhancedUserInfo.getDeviceid());
		// oldUserInfoService.checkReLogin(deviceId, _userInfo);
		// }
		// } else
		// ========================
		// if (platform == PlatformEnum.PC || platform == PlatformEnum.WAP) {
		// HttpServletResponse response = ((ServletRequestAttributes)
		// RequestContextHolder.getRequestAttributes()).getResponse();
		// if (response == null) {
		// HttpServletRequest request = ((ServletRequestAttributes)
		// RequestContextHolder.getRequestAttributes()).getRequest();
		// response = (HttpServletResponse)
		// request.getAttribute(Constants._WEB_LOCAL_RESPONSE);
		// }
		//
		// EnhancedUser _sessionEnhancedUser = null;
		// if (isRM) {
		// _sessionEnhancedUser = new EnhancedUser();
		// _sessionEnhancedUser.setId(enhancedUserInfo.getId());
		// _sessionEnhancedUser.setPassword(enhancedUserInfo.getPassword());
		// } else {
		// _sessionEnhancedUser = new EnhancedUser();
		// _sessionEnhancedUser.setId(enhancedUserInfo.getId());
		// }
		//
		// enhancedUserSession.setEnhancedUser(_sessionEnhancedUser);
		//
		// UserToken userToken = new UserToken(enhancedUserSession);
		// RememberMe rememberMe = null;
		// try {
		// rememberMe = UserTokenUtil.generateRememberMe(enhancedUserSession);
		// rememberMe.setRm(isRM);
		// } catch (Exception e) {
		// _LOGGER.error("[生成REMEMBERME异常]:" + e.getMessage(), e);
		// }
		// userToken.setRm(rememberMe);
		//
		// UserTokenUtil.writeUserTokenToCookie(userToken, response);
		// }

		userSessionService.updateUserSessionStatusForOnlyOneOnline(enhancedUserSession);

		return enhancedUserSession;
	}

	@Override
	public EnhancedUserSession loginWithPassword(String account, String password, boolean isEncoded, ThirdPartyTypeEnum thirdPartyType, PlatformEnum platform, String deviceId, boolean isRM,
			UserContext userContext) throws UserContextException {
		return this.login(account, password, true, isEncoded, thirdPartyType, platform, deviceId, isRM, userContext);
	}

	@Override
	public EnhancedUserSession loginWithNoPassword(String account, ThirdPartyTypeEnum thirdPartyType, PlatformEnum platform, String deviceId, boolean isRM, UserContext userContext)
			throws UserContextException {
		return this.login(account, null, false, false, thirdPartyType, platform, deviceId, isRM, userContext);
	}

}
